package com.hsj.busmanager.controller;

import com.hsj.busmanager.api.UserBean;
import com.hsj.busmanager.service.NewsService;
import com.hsj.busmanager.util.R;
import com.hsj.busmanager.util.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class HomeController {

    @Autowired
    private NewsService newsService;

    @RequestMapping(value = "/")
    public String index2() {
       return  index();
    }

    @RequestMapping(value = "/index")
    public String index(){
        return "/login";
    }


    /**
     * 获取验证码
     * @param request
     * @param response
     */
    @GetMapping("getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        }catch (Exception e){
            System.out.println("验证码错误============！");
            e.printStackTrace();
        }
    }


    /**
     * 获取当前用户未读消息数量
     * @param request
     * @return
     */
    @RequestMapping(value = "getUnReadCount")
    @ResponseBody
    public R getUnReadCount(HttpServletRequest request){
        UserBean user = (UserBean)request.getSession().getAttribute("user");
        int count = newsService.getUnReadCount(user.getId());
        return R.ok("count",count);
    }


    @RequestMapping(value = "logout")
    public ModelAndView logout(HttpServletRequest request,ModelAndView model){
        request.getSession().removeAttribute("user");
        model.setViewName("/login");
        return model;
    }
}
